package com.rad.datastat.receiver;

import java.text.SimpleDateFormat;
import java.util.Locale;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager.NameNotFoundException;

import com.rad.datastat.database.AppMd5DB;
import com.rad.datastat.event.PackageChangeEvent;
import com.rad.datastat.model.AppMd5Info;
import com.rad.datastat.service.DatastatService;
import com.rad.datastat.utils.ApplicationUtil;
import com.rad.datastat.utils.ArrivalPrefs;
import com.rad.datastat.utils.SimUtil;
import com.rad.datastat.utils.UsbControlUtil;
import com.rad.datastat.utils.Utils;
import com.rad.net.protocol.android.utils.LogUtils;
import com.rad.statistics.android.StatisticsAgent;

/**
 * 类说明：
 * 
 * @author Baker.li
 * @date 2014年3月11日
 * @version 1.0
 */

public class PackageReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent == null) {
			return;
		}

		LogUtils.e("RadStatistics", "PackageReceiver startDatastatService");
		Intent i = new Intent(context, DatastatService.class);
		context.startService(i);

		String packageName = intent.getDataString();
		if (packageName != null && packageName.length() > 0) {
			packageName = packageName.substring(packageName.lastIndexOf(':') + 1);
		}
		if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {
			sendPackageChangeEvent(context, "install", packageName);
			saveAppToDB(context, packageName);
		} else if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
			sendPackageChangeEvent(context, "uninstall", packageName);
		}
	}

	private void saveAppToDB(Context context, String packageName) {
		ApplicationInfo ai;
		try {
			ai = ApplicationUtil.getApplicationInfo(context, packageName);
			AppMd5Info info = new AppMd5Info();
			info.setPkgName(packageName);
			info.setAppName(ApplicationUtil.getAppName(context, ai));
			info.setMd5(ApplicationUtil.getFileMD5(ai.publicSourceDir));
			AppMd5DB.instance(context).save(info);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	private void sendPackageChangeEvent(Context context, String changeType, String pkgName) {
		PackageChangeEvent event = new PackageChangeEvent();
		try {
			event.setEventName("package_change_event");
			event.setChangeType(changeType);
			event.setAppPackage(pkgName);
			event.setUsbConnect(ArrivalPrefs.getUsbConnected(context));
			event.setUsbDebug(UsbControlUtil.isUSBDebugEnable(context));
			event.setSimReady(SimUtil.isSimIn(context));
			event.setGprsConnect(Utils.isGprs(context));
			event.setWifiConnect(Utils.isWiFi(context));
			if ("install".endsWith(changeType)) {
				ApplicationInfo ai = ApplicationUtil.getApplicationInfo(context, pkgName);
				event.setAppName(ApplicationUtil.getAppName(context, ai));
				event.setMd5(ApplicationUtil.getFileMD5(ai.publicSourceDir));
				
				Intent bc = new Intent("com.jy.appmarket.action.INNERINSTALLED");
				bc.putExtra("extra_name", event.getAppName());
				bc.putExtra("extra_pkg", pkgName);
				bc.putExtra("extra_md5", event.getMd5());
				context.sendBroadcast(bc);
			} else if ("uninstall".endsWith(changeType)) {
				AppMd5Info info = AppMd5DB.instance(context).queryByPkgName(pkgName);
				if (info != null) {
					event.setAppName(info.getAppName());
					event.setMd5(info.getMd5());
				}
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

		showPackageChangeEventLog(context, event);
		StatisticsAgent.onEvent(context, event);
	}

	private void showPackageChangeEventLog(Context context, PackageChangeEvent event) {
		if (!LogUtils.DEBUG) {
			return;
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
				Locale.getDefault());
		StringBuffer msg = new StringBuffer();
		msg.append("date=" + dateFormat.format(System.currentTimeMillis()) + "\n");
		msg.append("changeType=" + event.getChangeType() + "\n");
		msg.append("appName=" + event.getAppName() + "\n");
		msg.append("appPackage=" + event.getAppPackage() + "\n");
		msg.append("md5=" + event.getMd5() + "\n");
		msg.append("usbConnect=" + ArrivalPrefs.getUsbConnected(context) + "\n");
		msg.append("usbDebug=" + UsbControlUtil.isUSBDebugEnable(context) + "\n");
		msg.append("simReady=" + SimUtil.isSimIn(context) + "\n");
		msg.append("gprsConnect=" + Utils.isGprs(context) + "\n");
		msg.append("wifiConnect=" + Utils.isWiFi(context) + "\n");
		msg.append("========================\n");
		LogUtils.i("PackageChangeEvent", msg.toString());
	}
}
